package be.novelfaces.component.numpaddecsep;

import java.io.IOException;
import java.text.DecimalFormatSymbols;
import java.util.Locale;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.apache.commons.lang.StringUtils;

import be.novelfaces.component.encoder.Encoder;
import be.novelfaces.component.util.js.JSONBuilder;
import be.novelfaces.component.util.js.JavaScriptWriter;

public class NumpadDecimalSeparatorJSEncoder implements Encoder {

	static final String SEPARATOR = "separator";

	public void encode(FacesContext context, UIComponent component)
			throws IOException {
		JavaScriptWriter
				.getInstance()
				.startElement()
				.getJavaSriptConstructorWriterBuilder()
				.withNamespace("NovelFaces")
				.withConstructor("numpadDecSeparator")
				.withStringParameter(component.getClientId())
				.withParameter(
						new JSONBuilder().withProperty(SEPARATOR,
								getSeparator(context, component)).build())
				.writeConstructor().endElement();
	}

	private String getSeparator(FacesContext context, UIComponent component) {
		if (StringUtils.isEmpty((String) component.getAttributes().get(
				SEPARATOR))
				|| component.getAttributes().get(SEPARATOR) == "DEFAULT") {
			return getDecimalSeparatorFromLocaleFromViewRoot(context);
		}
		return (String) component.getAttributes().get(SEPARATOR);
	}

	private String getDecimalSeparatorFromLocaleFromViewRoot(
			FacesContext context) {
		Locale locale = context.getViewRoot().getLocale();
		return String.valueOf(DecimalFormatSymbols.getInstance(locale)
				.getDecimalSeparator());
	}

}
